package deployr.cli;

import deployr.core.*;
import deployr.domain.*;

public class CreateUpdateFilesBytesResponder extends Responder {

	private final Workspace workspace;

	public CreateUpdateFilesBytesResponder(Workspace workspace) {
		this.workspace = workspace;
	}
	
	@Override
	protected boolean shouldRespond(String method, String requestURI) {
		return "POST".equals(method) && requestURI.matches(".*/updates/.*/files/.*/bytes.*");
	}

	@Override
	protected Result respondTo(String method, String requestURI, Input input) {

		String updateKey = requestURI.replaceAll(".*/updates/", "").replaceAll("/files.*", "");
		String name = requestURI.replaceAll(".*/updates/.*/files/", "").replaceAll("/bytes.*", "");

		IUpdate update = workspace.findUpdate(updateKey);
		if (notFound(update))
			return new Result(404);

		IDeliverable deliverable = update.addDeliverable(name, input.getStream());
	
		workspace.store(deliverable);
		
		return new Result(200);
	}
}
